package com.town.garden.config;


import cn.hutool.core.thread.ThreadFactoryBuilder;
import com.town.garden.propertites.ScheduleProperties;
import lombok.AllArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.*;

/**
 * @Description 初始化线程池参数
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022/4/22
 */
@Configuration
@EnableScheduling
@EnableConfigurationProperties(value = ScheduleProperties.class)
@AllArgsConstructor
public class ScheduleConfig implements SchedulingConfigurer {
    private final ScheduleProperties scheduleProperties;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(getExecutor());
    }

    /**
     * 获取线程池
     *
     * @return 返回队列
     */
    @Bean
    public ScheduledExecutorService getExecutor() {
        //线程名称
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNamePrefix("schedule-pool-").build();
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(scheduleProperties.getCorePoolSize(), namedThreadFactory, new ThreadPoolExecutor.CallerRunsPolicy());
        //核心线程数
        executor.setCorePoolSize(scheduleProperties.getCorePoolSize());
        //拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //最大线程数
        executor.setMaximumPoolSize(scheduleProperties.getMaxPoolSize());
        //允许线程空闲时间(秒)
        executor.setKeepAliveTime(scheduleProperties.getAllowIdleTime(), TimeUnit.SECONDS);
        return executor;
    }
}
